import Cookies from 'js-cookie'
import DateUtils from '../common/utils/DateUtils'
import {profile} from '../config/base'
import axios from '../api/axios_config'
let userToken = null

export default {
  clearCookie:()=>{
    Cookies.remove('token',{ path: '/' })
    Cookies.remove('refreshToken',{ path: '/' })
    Cookies.remove('expiredTime',{ path: '/' })
    Cookies.remove('tokenType',{ path: '/' })
    userToken=null
  },
  login:(username,password)=>{
    return new Promise(function (resolve, reject) {
      axios({
        url: profile.apiHost + '/auth/login',
        method: 'post',
        headers:{'Authorization': 'Basic d2ViYXBwOndlYmFwcA=='},
        data: {
          username: username,
          password: password
        }
      }).then((res) => {
        resolve(res)
        if (res.data.access_token) {
          this.updateLoginData(res.data)
        }
      }).catch(error => {
        reject(error);
      });
    })
  },
  updateLoginData: (data) => {
    let date = new Date()
    let expireIn = data.expires_in
    let expiredTime = new Date(date.getTime() + (expireIn * 1000))
    let tokenVal = {
      token: data.access_token,
      refreshToken: data.refresh_token,
      expiredTime: expiredTime.Format('yyyy-MM-dd hh:mm:ss'),
      tokenType: data.token_type
    }
    for (let i in tokenVal) {
      Cookies.set(i, tokenVal[i], {
        expires: expiredTime,
        path: '/',
      })
    }
    userToken = tokenVal.tokenType + ' ' + tokenVal.token
  }, getUserToken: () => {
    if (profile.isDev)
      return true
    if (!userToken) {
      let tokenType = Cookies.get('tokenType')
      if (tokenType)
        userToken = tokenType + ' ' + Cookies.get('token')
    }
    return userToken
  },refreshToken:()=>{
    if (profile.isDev)
      return
    let expiredTime = Cookies.get("expiredTime")
    if (expiredTime) {
      let interval = DateUtils.getInterval(DateUtils.parserDate(expiredTime), new Date(), 'm')
      if (interval < 10) {
        //小于10分钟，去refresh
        let refreshToken = Cookies.get("refreshToken")
        if (refreshToken) {
          axios({
            url: profile.apiHost + '/auth/oauth/refreshToken',
            method: 'post',
            headers:{'Authorization': 'Basic d2ViYXBwOndlYmFwcA=='},
            data: "grant_type=refresh_token&refresh_token=" + refreshToken
          }).then((res) => {
            if (res.access_token) {
              this.updateLoginData(res)
            }
          })
        }
      }
    }
  }
}
